<template>
  <div class="info-left-content">
    <div class="left-content">
      <div class="on">
        <span>在这里可以搜索出的商品 </span>
      </div>
      <div class="middle">
        <span>离工地更近、价格最优、运费最低</span>
      </div>
      <div class="down">
        <el-form ref="form" label-width="auto">
          <el-form-item label="收货地址:">
            <span @click="openMap">
              <el-input v-if="ruleForm.address.addressTitle" v-model="ruleForm.address.addressTitle" type="text" placeholder="点击选择收货地址" />
              <el-input v-else v-model="ruleForm.address.receiveAddress" type="text" placeholder="点击选择收货地址" />
            </span>
          </el-form-item>
          <el-form-item label="主 分 类:" id="main-category-select">
            <el-select v-model="ruleForm.mainCategoryVal" placeholder="请选择主分类" value-key="id" @visible-change="mainCategoryItemShow">
              <el-option
                v-for="item in mainCategoryList"
                :key="item.id"
                :label="item.categoryName"
                :value="item"
              >
                <span v-if="item.noDisable">{{ item.categoryName }}</span>
                <span v-else style="color: #C0C4CC">{{ item.categoryName }}</span>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="子 分 类:" id="sub-category-select">
            <el-select v-model="ruleForm.subCategoryVal" value-key="id" placeholder="请选择子分类" @visible-change="subCategoryItemShow">
              <el-option
                v-for="item in subCategoryList"
                :key="item.id"
                :label="item.categoryName"
                :value="item"
              >
                <span v-if="item.noDisable">{{ item.categoryName }}</span>
                <span v-else style="color: #C0C4CC">{{ item.categoryName }}</span>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item v-if="ruleForm.subCategoryVal.id && ruleForm.subCategoryVal.standardProa" id="category-prop-select1" :label="`${ruleForm.subCategoryVal.standardProa }：`">
            <el-select v-model="ruleForm.attributeVal[0]" :loading="attributeLoading[0]" placeholder="请选择属性" value-key="id" @visible-change="cateProp1ItemShow">
              <el-option
                v-for="item in sortItem(attributeInfo.filter(temp => temp.propType === (1)), false)"
                :key="item.id"
                :label="item.propValue"
                :value="item"
              >
                <span v-if="item.noDisable">{{ item.propValue }}</span>
                <span v-else style="color: #C0C4CC">{{ item.propValue }}</span>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item v-if="ruleForm.subCategoryVal.id && ruleForm.subCategoryVal.standardProb" id="category-prop-select2" :label="`${ruleForm.subCategoryVal.standardProb }：`">
            <el-select v-model="ruleForm.attributeVal[1]" :loading="attributeLoading[1]" placeholder="请选择属性" value-key="id" @visible-change="cateProp2ItemShow">
              <el-option
                v-for="item in sortItem(attributeInfo.filter(temp => temp.propType === (2)), false)"
                :key="item.id"
                :label="item.propValue"
                :value="item"
              >
                <span v-if="item.noDisable">{{ item.propValue }}</span>
                <span v-else style="color: #C0C4CC">{{ item.propValue }}</span>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item v-if="ruleForm.subCategoryVal.id && ruleForm.subCategoryVal.standardProc" id="category-prop-select3" :label="`${ruleForm.subCategoryVal.standardProc }：`">
            <el-select v-model="ruleForm.attributeVal[2]" :loading="attributeLoading[2]" placeholder="请选择属性" value-key="id" @visible-change="cateProp3ItemShow">
              <el-option
                v-for="item in sortItem(attributeInfo.filter(temp => temp.propType === (3)), false)"
                :key="item.id"
                :label="item.propValue"
                :value="item"
              >
                <span v-if="item.noDisable">{{ item.propValue }}</span>
                <span v-else style="color: #C0C4CC">{{ item.propValue }}</span>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item v-if="ruleForm.subCategoryVal.id && ruleForm.subCategoryVal.standardProd" id="category-prop-select4" :label="`${ruleForm.subCategoryVal.standardProd }：`">
            <el-select v-model="ruleForm.attributeVal[3]" :loading="attributeLoading[3]" placeholder="请选择属性" value-key="id" @visible-change="cateProp4ItemShow">
              <el-option
                v-for="item in sortItem(attributeInfo.filter(temp => temp.propType === (4)), false)"
                :key="item.id"
                :label="item.propValue"
                :value="item"
              >
                <span v-if="item.noDisable">{{ item.propValue }}</span>
                <span v-else style="color: #C0C4CC">{{ item.propValue }}</span>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item v-if="ruleForm.subCategoryVal.id && ruleForm.subCategoryVal.standardProe" id="category-prop-select5" :label="`${ruleForm.subCategoryVal.standardProe }：`">
            <el-select v-model="ruleForm.attributeVal[4]" :loading="attributeLoading[4]" placeholder="请选择属性" value-key="id" @visible-change="cateProp5ItemShow">
              <el-option
                v-for="item in sortItem(attributeInfo.filter(temp => temp.propType === (5)), false)"
                :key="item.id"
                :label="item.propValue"
                :value="item"
              >
                <span v-if="item.noDisable">{{ item.propValue }}</span>
                <span v-else style="color: #C0C4CC">{{ item.propValue }}</span>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item :label="ruleForm.subCategoryVal.categoryUnit | formatBuyNumLabel">
            <el-input-number v-model="ruleForm.buyNum" :min="1" :max="100000" :precision="0" label="请输入采购数量" />
          </el-form-item>
        </el-form>
      </div>
      <div class="footer">
        <button type="button" class="btn-footer" @click="searchDetail">立即搜索</button>
      </div>
      <div class="shade" />
    </div>
    <ChooseMap v-if="showMap" :location="{lat: ruleForm.address.latitude, lng: ruleForm.address.longitude}" @concel="concel" @submitMap="submitMap" />
  </div>
</template>
<script>
import ChooseMap from '@/components/ChooseMap'
import { toProductList } from '@/js/product'
import { loadMainCategory, loadsubCategory, loadAttribute, loadPropValExistSpu } from '@/api/search/index'
export default {
  name: 'InformationSearch',
  components: {
    ChooseMap
  },
  filters: {
    formatBuyNumLabel(val) {
      return val ? `采购数量(${val})：` : '采购数量：'
    }
  },
  data() {
    return {
      showMap: false,
      mainCategoryList: [], // 主分类列表
      subCategoryList: [], // 子分类列表
      attributeInfo: [], // 关键属性列表
      attributeLoading: [true, true, true, true, true], // 关键属性下拉框打开时的标志
      ruleForm: {
        mainCategoryVal: {}, // 已选的主分类值
        subCategoryVal: {}, // 已选的子分类值
        attributeVal: [{}, {}, {}, {}, {}], // 所选属性值的id
        address: {}, // 地址
        buyNum: 1 // 采购数量
      }
    }
  },
  watch: {
    // 地址变化加载主分类
    'ruleForm.address': {
      handler: function() {
        this.getMainCate()
      }
    },
    // 动态加载子分类
    'ruleForm.mainCategoryVal': {
      handler: function(newVal) {
        this.ruleForm.subCategoryVal = {}
        this.ruleForm.attributeVal = [{}, {}, {}, {}, {}]
        this.attributeInfo = []
        this.subCategoryList = []
        if (newVal.id) {
          const lat = this.ruleForm.address.latitude
          const lng = this.ruleForm.address.longitude
          const mainCategoryId = newVal.id
          loadsubCategory({ mainCategoryId, lng, lat }).then(res => {
            if (res.data && res.data.existIds && res.data.existIds.length > 0) {
              res.data.list.forEach(temp => {
                temp.noDisable = res.data.existIds.includes(temp.id)
              })
            } else {
              res.data.list.forEach(temp => { temp.noDisable = false })
            }
            this.subCategoryList = this.sortItem(res.data.list, true)
          })
        }
      }
    },
    // 动态加载属性
    'ruleForm.subCategoryVal': {
      handler: function(newVal) {
        this.ruleForm.attributeVal = [{}, {}, {}, {}, {}]
        if (newVal.id) {
          loadAttribute(newVal.id).then(res => {
            this.attributeInfo = res.data
          })
        } else {
          this.attributeInfo = []
        }
      }
    }

  },
  created() {
    this.getMainCate()
  },
  methods: {
    // 是否展现主分类下拉框
    mainCategoryItemShow(flag) {
      const lat = this.ruleForm.address.latitude
      const lng = this.ruleForm.address.longitude
      if (flag && (!lat || !lng)) {
        document.getElementById('main-category-select').getElementsByClassName('el-select')[0].click()
        this.$message.error('请先选择收货地址!')
      }
    },
    // 是否展现子分类下拉框
    subCategoryItemShow(flag) {
      const lat = this.ruleForm.address.latitude
      const lng = this.ruleForm.address.longitude
      if (flag) {
        if (!lat || !lng) {
          document.getElementById('sub-category-select').getElementsByClassName('el-select')[0].click()
          this.$message.error('请先选择收货地址!')
        } else if (!this.ruleForm.mainCategoryVal.id) {
          document.getElementById('sub-category-select').getElementsByClassName('el-select')[0].click()
          this.$message.error('请先选择主分类!')
        }
      }
    },
    // 是否展现属性值1下拉框
    cateProp1ItemShow(flag) {
      this.loadCateProp(0, flag)
    },
    // 是否展现属性值2下拉框
    cateProp2ItemShow(flag) {
      this.loadCateProp(1, flag)
    },
    // 是否展现属性值3下拉框
    cateProp3ItemShow(flag) {
      this.loadCateProp(2, flag)
    },
    // 是否展现属性值4下拉框
    cateProp4ItemShow(flag) {
      this.loadCateProp(3, flag)
    },
    // 是否展现属性值5下拉框
    cateProp5ItemShow(flag) {
      this.loadCateProp(4, flag)
    },
    // 加载属性值
    loadCateProp(index, flag) {
      const lat = this.ruleForm.address.latitude
      const lng = this.ruleForm.address.longitude
      if (flag) {
        this.$set(this.attributeLoading, index, true)
        if (!lat || !lng) {
          document.getElementById(`category-prop-select${index + 1}`).getElementsByClassName('el-select')[0].click()
          this.$message.error('请先选择收货地址!')
        } else {
          const proaId = this.ruleForm.attributeVal[0].id
          const probId = this.ruleForm.attributeVal[1].id
          const procId = this.ruleForm.attributeVal[2].id
          const prodId = this.ruleForm.attributeVal[3].id
          const proeId = this.ruleForm.attributeVal[4].id
          const mainCategoryId = this.ruleForm.mainCategoryVal.id
          const childCategoryId = this.ruleForm.subCategoryVal.id
          loadPropValExistSpu(index + 1, { mainCategoryId, childCategoryId, lng, lat, proaId, probId, procId, prodId, proeId }).then(res => {
            const data = this.attributeInfo.filter(temp => temp.propType === (index + 1))
            if (res.data) {
              data.forEach(temp => {
                temp.noDisable = res.data.includes(temp.id)
              })
            }
            let temp = {}
            if (this.ruleForm.attributeVal[index].id) {
              temp = data.filter(temp => temp.id === this.ruleForm.attributeVal[index].id)
              temp = temp.length > 0 ? temp[0] : {}
            }
            this.ruleForm.attributeVal.splice(index, 1, temp)
          }).finally(() => {
            this.$set(this.attributeLoading, index, false)
          })
        }
      }
    },

    // 获取主分类列表
    getMainCate() {
      const lat = this.ruleForm.address.latitude
      const lng = this.ruleForm.address.longitude
      let param = {}
      if (lat && lng) {
        param = { lat, lng }
      }
      loadMainCategory(param).then(res => {
        if (res.data && res.data.existIds && res.data.existIds.length > 0) {
          res.data.list.forEach(temp => {
            temp.noDisable = res.data.existIds.includes(temp.id)
          })
        } else {
          res.data.list.forEach(temp => { temp.noDisable = false })
        }
        this.mainCategoryList = this.sortItem(res.data.list, true)
      })
    },
    // 选择项排序
    sortItem(array, isFlag) {
      array = isFlag ? array : JSON.parse(JSON.stringify(array))
      array.sort((a, b) => {
        return (a.noDisable ? 0 : 1) - (b.noDisable ? 0 : 1)
      })
      return array
    },
    openMap() {
      this.showMap = true
    },
    concel() {
      this.showMap = false
    },
    submitMap(address) {
      this.showMap = false
      this.ruleForm.address = address
    },
    searchDetail() {
      if (!this.ruleForm.address.latitude || !this.ruleForm.address.longitude) {
        this.$message.error('请点击选择收货地址')
        return
      } else if (!this.ruleForm.mainCategoryVal.id) {
        this.$message.error('请选择主分类')
        return
      } else if (!this.ruleForm.subCategoryVal.id) {
        this.$message.error('请选择子分类')
        return
      } else {
        const subCategoryVal = this.ruleForm.subCategoryVal
        const attributeVal = this.ruleForm.attributeVal
        if (subCategoryVal.standardProa && !attributeVal[0].id) {
          this.$message.error(`请选择${subCategoryVal.standardProa}`)
          return
        } else if (subCategoryVal.standardProb && !attributeVal[1].id) {
          this.$message.error(`请选择${subCategoryVal.standardProb}`)
          return
        } else if (subCategoryVal.standardProc && !attributeVal[2].id) {
          this.$message.error(`请选择${subCategoryVal.standardProc}`)
          return
        } else if (subCategoryVal.standardProd && !attributeVal[3].id) {
          this.$message.error(`请选择${subCategoryVal.standardProd}`)
          return
        } else if (subCategoryVal.standardProe && !attributeVal[4].id) {
          this.$message.error(`请选择${subCategoryVal.standardProe}`)
          return
        }
      }
      const sortType = 0
      const address = this.ruleForm.address
      const mainCategory = this.ruleForm.mainCategoryVal
      const childCategory = this.ruleForm.subCategoryVal
      const proaId = this.ruleForm.attributeVal[0].id
      const probId = this.ruleForm.attributeVal[1].id
      const procId = this.ruleForm.attributeVal[2].id
      const prodId = this.ruleForm.attributeVal[3].id
      const proeId = this.ruleForm.attributeVal[4].id
      const buyNum = this.ruleForm.buyNum
      const searchRange = 50
      const info = {}
      info.proa = this.ruleForm.attributeVal[0].propValue
      info.prob = this.ruleForm.attributeVal[1].propValue
      info.proc = this.ruleForm.attributeVal[2].propValue
      info.prod = this.ruleForm.attributeVal[3].propValue
      info.proe = this.ruleForm.attributeVal[4].propValue
      toProductList(this, { sortType, childCategory, mainCategory, proaId, probId, procId, prodId, proeId, address, buyNum, searchRange, info })
    }
  }
}
</script>
<style scoped lang="scss">
@import "@/assets/style/common.scss";
.info-left-content {
  width: 305px;
  height: 450px;
  margin-right: 20px;
  background: #e9e2d4;
  margin-top: 26px;
  position: relative;
  .on {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 191px;
    height: 40px;
    background: rgba(247, 245, 240, 1);
    border-radius: 0px 0px 20px 0px;
    margin: 2px 0 0 3px;
    font-size: 14px;
  }
  .middle {
    width: 270px;
    height: 25px;
    font-size: 18px;
    font-family: PingFang SC;
    font-weight: bold;
    line-height: 25px;
    color: rgba(242, 97, 34, 1);
    opacity: 1;
    margin: 21px 0 0 14px;
  }
  .shade{
    width: 13px;
    height: 288px;
    background: #e9e2d4;
    position: absolute;
    top: 110px;
    right: 0;
  }
  .down {
    margin: 25px 0 0 10px;
    overflow-y: auto;
    min-height: 170px;
    max-height: 280px;
    .input {
      width: 164px;
      height: 30px;
      margin-bottom: 10px;
      border: 0;
      outline: none;
    }
    .number {
      display: flex;
      align-items: center;
      .btn {
        width: 29px;
        height: 28px;
        background: rgba(245, 247, 250, 1);
        border: 1px solid rgba(220, 223, 230, 1);
      }
      .number-text {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 74px;
        height: 28px;
        background: rgba(255, 255, 255, 1);
        border: 1px solid rgba(220, 223, 230, 1);
      }
    }
  }
  .footer {
    margin: 10px 29px 0 116px;
    .btn-footer {
      display: flex;
      justify-content: center;
      align-items: center;
      color: #ffffff;
      width: 164px;
      height: 30px;
      background: #f26122;
      border-radius: 8px;
    }
  }
}

/deep/ .down{
  .el-input__inner{
    height: 30px;
    width: 164px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    display: inline-block;
    width: 100%;
  }
  .el-form-item{
    margin-bottom: 0px;
  }
  .el-input-number{
    width: 164px;
    line-height: 28px;
  }
}
/deep/ .middle-on {
  .el-carousel__indicators--outside {
    bottom: 0px;
    text-align: center;
    position: absolute;
    left: 240px;
  }
}
</style>
